#!/bin/bash -e

# SPDX-FileCopyrightText: Copyright (c) 2022-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

shopt -s extglob

# Defaults
test_set="all"
curdir=$(dirname "$(readlink -f "$0")")
failure_sets=""

if [[ $# -ge 1 ]]; then
    test_set=$1
fi

IFS="," read -r -a test_set <<< "$test_set"

function on_exit()
{
    set +e
    if [ -n "$failure_sets" ]; then
        echo Tests FAILED: ${failure_sets:1}
        exit 1
    fi
}

function on_error()
{
    set +e
    echo Tests FAILED
    exit 1
}

function on_interrupt()
{
    echo Tests INTERRUPTED
}

trap 'on_error' ERR
trap 'on_interrupt' SIGINT
trap 'on_exit' EXIT

function run()
{
    local testexec=$1
    shift
    local test_tags=("$@")

    # Check if all filters in test_set match at least one tag in test_tags
    local all_filters_matched=true
    for filter in "${test_set[@]}"
    do
        if [ "$filter" == "all" ]; then
            # "all" filter matches everything
            continue
        fi

        # Check if this filter matches any tag
        local filter_matched=false
        for tag in "${test_tags[@]}"
        do
            if [ "$tag" == "$filter" ]; then
                filter_matched=true
                break
            fi
        done

        if [ "$filter_matched" == "false" ]; then
            all_filters_matched=false
            break
        fi
    done

    if [ "$all_filters_matched" == "true" ]; then
        echo "Running $testexec test suite..."
        set +e
        NVCV_LEAK_DETECTION=abort "$curdir/$testexec"
        if [ $? -ne 0 ]; then
            failure_sets=$failure_sets,$testexec
        fi
        set -e
        return
    fi

    echo "Skipping $testexec test suite..."
}
